<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 首页接口
 */
class Goods extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     * 
     */
    public function index()
    {
        $sort = Db::name('sort')->order('num')->select();
        return json_encode($sort);
    }
    public function goodslist(){
        $params = $this->request->post();
        if(isset($params['type'])){
           if($params['type'] == 1){
               $status = $params['desc'] == 'true'?'sum asc':'sum desc';
           }elseif ($params['type'] == 2){
               $status = $params['desc'] == 'true'?'price asc':'price desc';
           }else{
               $status = 'id desc';
           }
        }else{
            $status = 'id desc';
        }
        $res = Db::name('commodity')
            ->where('sort_id',$params['sortId'])
            ->order($status)
            ->select();
        return json_encode($res);
    }
    public function detail(){
        $params = $this->request->post();
        $res = Db::name('commodity')->where('id',$params['id'])->find();
        $images = explode(',',$res['images']);
        $people = model('People')->people($params['openid']);
        $address = Db::name('address')->where('people_id',$people['id'])->where('isdefault',1)->find();
        $norm = json_decode($res['norm'],true);
        foreach ($norm as $k=>$v){
            $norm[$k]['size'] = explode(' ',$v['size']);
        }
        return json_encode(['res'=>$res,'norm'=>$norm,'address'=>$address,'images'=>$images]);
    }
    public function order(){
        $params = $this->request->post();
        $student = model('People')->people($params['openid']);
        $order_no = date('Ymd').'ZUDIAN'.substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $arr = array(
            'people_id'    => $student['id'],
            'order_no'      => $order_no,
            'price'         => $params['price'],
            'commodity_id'     => $params['id'],
            'sum'         => $params['sum'],
            'address'       => $params['address'],
            'phone'         => $params['phone'],
            'ursername'     => $params['ursername'],
            'color'     => $params['color'],
            'size'     => $params['size'],
            'createtime'    => time()
        );
        $res = Db::name('order')->insert($arr);
        return $res?$order_no:400;
    }
}
